using System.Text.Json;
using Microsoft.Extensions.Logging;

namespace _3Dto2D.Configuration;

public class ConfigurationManager
{
    private readonly ILogger<ConfigurationManager> _logger;
    private readonly string _configPath;
    private RenderSettings? _settings;

    public ConfigurationManager(ILogger<ConfigurationManager> logger, string configPath = "settings.json")
    {
        _logger = logger;
        _configPath = configPath;
    }

    public RenderSettings Settings => _settings ??= LoadSettings();

    public RenderSettings LoadSettings()
    {
        try
        {
            if (!File.Exists(_configPath))
            {
                _logger.LogInformation("Configuration file not found, creating default settings");
                var defaultSettings = new RenderSettings();
                SaveSettings(defaultSettings);
                return defaultSettings;
            }

            var json = File.ReadAllText(_configPath);
            var settings = JsonSerializer.Deserialize<RenderSettings>(json, GetJsonOptions());
            
            _logger.LogInformation("Configuration loaded successfully");
            return settings ?? new RenderSettings();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to load configuration, using defaults");
            return new RenderSettings();
        }
    }

    public async Task SaveSettingsAsync(RenderSettings settings)
    {
        try
        {
            var json = JsonSerializer.Serialize(settings, GetJsonOptions());
            await File.WriteAllTextAsync(_configPath, json);
            _settings = settings;
            
            _logger.LogInformation("Configuration saved successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to save configuration");
            throw;
        }
    }

    public void SaveSettings(RenderSettings settings)
    {
        try
        {
            var json = JsonSerializer.Serialize(settings, GetJsonOptions());
            File.WriteAllText(_configPath, json);
            _settings = settings;
            
            _logger.LogInformation("Configuration saved successfully");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to save configuration");
            throw;
        }
    }

    private static JsonSerializerOptions GetJsonOptions()
    {
        return new JsonSerializerOptions
        {
            WriteIndented = true,
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            Converters = { new ColorJsonConverter() }
        };
    }
}
